package com.mengzhilan.util;

import com.mengzhilan.base.Named;
import org.xlp.tree.TreeNode;
import org.xlp.utils.XLPStringUtil;
import org.xlp.utils.collection.XLPCollectionUtil;

import java.util.List;

/**
 * Description: 树查找工具类
 * <br/>date: 2023/12/8 10:59
 *
 * @version 1.0
 * @author: xlp
 */
public class TreeFindUtils {
    /**
     * 根据名称查找树的一个节点，第一个参数的元素必须是{@link org.xlp.tree.TreeNode}的实现，否则会抛出类转换异常
     * @param treeNodes 查找的数据
     * @param name 查找条件
     * @return 返回查找数据，假如参数为null或未找到，则返回null
     */
    @SuppressWarnings("all")
    public static Named findTreeNodeByName(List<Named> treeNodes, String name){
        if (XLPCollectionUtil.isEmpty(treeNodes) || XLPStringUtil.isEmpty(name)){
            return null;
        }
        for (Named named : treeNodes) {
            String treeName = named.getName();
            // 查找到数据直接返回
            if (treeName != null && treeName.contains(name)) return named;
            TreeNode treeNode = (TreeNode) named;
            List children = treeNode.getChildren();
            named = findTreeNodeByName(children, name);
            if (named != null) return named;
        }
        return null;
    }
}
